package app.backend.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.Map;

/**
 * @author yangjianbin
 * @since 2022/7/26 17:36
 */
public class JwtUtils {
    //定义自己的密钥
    private static final String SECRET = "token!ALUB(#$bula%$#.";

    /**
     * 生成token
     *
     * @param payload 传入的有效负荷
     * @return
     */
    public static String createToken(Map<String, String> payload, int timeout) {
        JWTCreator.Builder builder = JWT.create();
        payload.forEach(builder::withClaim);
        Date expiresAt = new Date(System.currentTimeMillis() + timeout * 1000);
        builder.withExpiresAt(expiresAt);
        return builder.sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * 验证token
     * verify
     *
     * @param token
     * @return
     */
    public static DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }
}
